<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui'

import { computed, h, onMounted, ref } from 'vue'

import { AuthenticationLogin, z } from '@vben/common-ui'
import { $t } from '@vben/locales'

import { fetchCaptcha } from '#/api'
import { useAuthStore } from '#/store'

defineOptions({ name: 'Login' })

const authStore = useAuthStore()

// 图片验证码
function useCaptcha() {
    const captchaImg = ref<string>('')
    const captchaImgKey = ref<string>('')

    async function updateCaptcha() {
        const data = await fetchCaptcha()

        captchaImg.value = data.captcha
        captchaImgKey.value = data.key
    }

    onMounted(() => {
        updateCaptcha()
    })

    return {
        updateCaptcha,
        captchaImg,
        captchaImgKey
    }
}

const { captchaImg, updateCaptcha, captchaImgKey } = useCaptcha()

const formSchema = computed((): VbenFormSchema[] => {
    return [
        {
            component: 'VbenInput',
            componentProps: {
                placeholder: $t('authentication.usernameTip')
            },

            fieldName: 'username',
            label: $t('authentication.username'),
            rules: z.string().min(1, { message: $t('authentication.usernameTip') })
        },
        {
            component: 'VbenInputPassword',
            componentProps: {
                placeholder: $t('authentication.password')
            },
            fieldName: 'password',
            label: $t('authentication.password'),
            rules: z.string().min(1, { message: $t('authentication.passwordTip') })
        },
        {
            component: 'VbenInput',
            fieldName: 'captcha',
            componentProps: {
                placeholder: $t('authentication.codeCommonTip')
            },
            rules: z.string().min(1, { message: $t('authentication.codeCommonTip') }),
            suffix: () => {
                return h('img', {
                    src: captchaImg.value,
                    style: {
                        width: 'calc(100% - 10px)',
                        height: '40px',
                        marginLeft: '10px',
                        cursor: 'pointer',
                        borderRadius: '4px'
                    },
                    onClick: updateCaptcha
                })
            }
        }
    ]
})
const AuthenticationLoginRef = ref<InstanceType<typeof AuthenticationLogin>>()

async function onSubmit(data: any) {
    try {
        await authStore.authLogin({
            password: data.password,
            username: data.username,
            captcha: data.captcha,
            key: captchaImgKey.value
        })
    } catch {
        updateCaptcha()
        const formApi = AuthenticationLoginRef.value?.getFormApi()

        if (formApi) {
            // 登录失败重置验证码
            formApi.setFieldValue('captcha', '')
        }
    }
}
</script>

<template>
    <AuthenticationLogin
        ref="AuthenticationLoginRef"
        :form-schema="formSchema"
        :loading="authStore.loginLoading"
        :show-code-login="true"
        :show-forget-password="false"
        :show-qrcode-login="false"
        :show-register="false"
        :show-remember-me="false"
        :show-third-party-login="false"
        @submit="onSubmit"
    />
</template>
